/**
 * @(#)Connect.java 2011-10-27 Copyright 2011 it.kedacom.com, Inc. All rights
 *                  reserved.
 */

package com.kedacom.ldap.unboundidsdk.demo;

import java.io.IOException;

import com.unboundid.ldap.sdk.Entry;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldif.LDIFException;
import com.unboundid.ldif.LDIFReader;
import com.unboundid.ldif.LDIFWriter;

/**
 * (用一句话描述类的主要功能)
 * @author xiaojinghai
 * @date 2011-10-27
 */

public class ImportUserFromLDIF {

	/**
	 * (用一句话描述方法的主要功能)
	 * @param args
	 */

	public static void main(String[] args) {
		String host = "172.16.3.11";
		int port = 389;
		String bindDN = "cn=manager,dc=com";
		String password = "itserver";
		LDAPConnection conn = null;
		String importFile = "ExportUsersFromDomino.ldif";
		String errorFile = "ImportErrors.ldif";
		int importCount = 0;
		int errorCount = 0;
		int totalCount = 0;
		try {
			conn = new LDAPConnection(host, port, bindDN, password);
			LDIFReader ldifReader = new LDIFReader(importFile);
			LDIFWriter ldifWriter = new LDIFWriter(errorFile);
			while (true) {
				Entry entry;
				try {
					entry = ldifReader.readEntry();
					if (entry == null) {
						System.err.println("All entries have been processed.");
						break;
					}
				} catch (LDIFException le) {
					if (le.mayContinueReading()) {
						System.err.println("A recoverable occurred while attempting to "
								+ "read an entry at or near line number " + le.getLineNumber() + ":  "
								+ le.getMessage());
						System.err.println("The entry will be skipped.");
						continue;
					} else {
						System.err.println("An unrecoverable occurred while attempting to "
								+ "read an entry at or near line number " + le.getLineNumber() + ":  "
								+ le.getMessage());
						System.err.println("LDIF processing will be aborted.");
						break;
					}
				} catch (IOException ioe) {
					System.err.println("An I/O error occurred while attempting to read " + "from the LDIF file:  "
							+ ioe.getMessage());
					System.err.println("LDIF processing will be aborted.");
					break;
				}
				totalCount++;
				try {
					conn.add(entry);
					importCount++;
					// System.out.println("Successfully added entry " +
					// entry.getDN());
				} catch (LDAPException le) {
					errorCount++;
					String errorMsg = "Unable to add entry " + entry.getDN() + " -- " + le.getMessage();
					ldifWriter.writeComment(errorMsg, true, false);
					ldifWriter.writeEntry(entry);
					// System.err.println("Unable to add entry " + entry.getDN()
					// + " -- " + le.getMessage());
				}
				System.out.println("已处理：" + totalCount);
			}

			ldifReader.close();
			ldifWriter.close();
			System.out.println("成功导入:" + importCount);
			System.out.println("未成功:" + errorCount);

		} catch (LDAPException e) {
			// TODO 尚未处理异常
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 尚未处理异常
			e.printStackTrace();
		}

	}
}
